var path = require('path');
var express = require('express');
const https = require('https');
const fs = require('fs');
const http = require('http');
const yun = express();
const os = require('os');
const logjs = require('./config/logjs.js'); // 日志中间件
const initRouter = require('./config/router-req.js')
// 读取证书,__dirname获取当前文件所在目录__filename是获取文件路径
let key = fs.readFileSync(path.join(__dirname, '/ssl/server.key'), 'utf8'),
    cert = fs.readFileSync(path.join(__dirname, '/ssl/server.pem'), 'utf8');
// 创建证书对象
let cas = { key, cert };

// 引入请求体中间处理
const bodyParser = require('body-parser');
const $common = require('./common/common-req.js')
// 日志配置
logjs.configPath = path.join(__dirname, "/config/json/logConfig.json")
// 创建服务器

// create application/json parser， 处理json格式
yun.use(bodyParser.json());
// create application/x-www-form-urlencoded parser，处理普通body格式
yun.use(bodyParser.urlencoded({ extended: false }));
// 监听静态资源
const staticPath = path.resolve('', path.join(__dirname, ''), '../public');
yun.use(`/${$common.projectName}/public`, express.static(staticPath));
console.log(staticPath)
// yun.use('/yun/public', express.static('public'));
let yunHttp = http.createServer(yun);
let yunHttps = https.createServer(cas, yun);
const getParam = (url) => {
    const _p = {}
    url.substring(url.indexOf('?')).split('&').map(item => {
        const _arr = item.split('=')
        _p[_arr[0]] = _arr[1]
    })
    return _p
}
// 跨域设置
yun.all("*", function(req, res, next) {
    // 请求拦截处理
	res.header('Access-Control-Allow-Origin', "*");
    // res.header('Access-Control-Allow-Headers', 'content-type');
	res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length,Authorization,Accept,X-Requested-With');
	res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
	res.header('X-Powered-By', '3.2.1')
	if (req.method == 'OPTIONS') res.sendStatus(200);
	// /让options请求快速返回/
	else {
        // let token = req.query.token ? req.query.token : req.body.token;
        // let userId = req.query.userId ? req.query.userId : req.body.userId;
        const whiteName = require('./config/json/whiteName.json')
        console.log('whiteName', req.pathname)
        console.log('---', req._parsedUrl.pathname)
        if (whiteName.indexOf(req._parsedUrl.pathname) === -1 && req.originalUrl.indexOf('uCenter') > -1) {
            let _token = req.headers.authorization
            console.log('_token', _token)
            if (!_token || $common.tokenArr.indexOf(_token) === -1) {
                res.send($common.setErrorData('鉴权失败，请先登录！'));
                return;
            }
        }
        next();
    }
});

// 激活路由
initRouter(yun, $common.projectName)

// 监听服务端口
yunHttp.listen($common.port, $common.hostname, function() {
	console.log(`服务器启动成功！-- http://${$common.hostname}:${$common.port}/${$common.projectName}`)
})
yunHttps.listen($common.ports, $common.hostname, function() {
	console.log(`服务器启动成功！-- https://${$common.hostname}:${$common.ports}/${$common.projectName}`)
})



